package com.framework.controller.system;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.framework.annotation.SystemLog;
import com.framework.controller.index.BaseController;
import com.framework.entity.ConsoleuserFormMap;
import com.framework.entity.ResFormMap;
import com.framework.entity.ResUserFormMap;
import com.framework.entity.ConsoleuserFormMap;
import com.framework.entity.UserRoleFormMap;
import com.framework.plugin.PageView;
import com.framework.util.Common;
import com.framework.util.PasswordHelper;

/**
 * 
 * @author framework 2015-11-19
 * @Email: g5874589652@126.com
 * @version 4.0v
 */
@Controller
@RequestMapping("/user/")
public class UserController extends BaseController {
	List<ResFormMap> res = null;

	@RequestMapping("list")
	public String listUI(Model model) throws Exception {
		res = findByRes();
		model.addAttribute("res", getButtomM(res));
		return Common.BACKGROUND_PATH + "/system/user/list";
	}

	@ResponseBody
	@RequestMapping("getButton")
	public String getButton() throws Exception {
		return getButtomB(res);
	}

	@ResponseBody
	@RequestMapping("findByPage")
	public PageView findByPage(String draw, String length, String start) throws Exception {
		ConsoleuserFormMap userFormMap = getFormMap(ConsoleuserFormMap.class);
		userFormMap.put("id", Common.findUserSessionId());
		userFormMap.put("$orderby", getorder());
		userFormMap.put("$search", getsearch());
		userFormMap = toFormMap(userFormMap, draw, length, start);
		pageView.setData(ConsoleuserFormMap.mapper().findUserPage(userFormMap));// 不调用默认分页,调用自已的mapper中findUserPage
		return pageView;
	}

	@RequestMapping("addUI")
	public String addUI(Model model) throws Exception {
		// 新增用户时寻找本用户能给新用户设定哪些上司
		ConsoleuserFormMap userFormMap = new ConsoleuserFormMap();
		String id = Common.findUserSessionId();
		userFormMap.put("id", id);
		List<ConsoleuserFormMap> list = userFormMap.mapper().findChildList(userFormMap);
		model.addAttribute("userlist", list);
		return Common.BACKGROUND_PATH + "/system/user/add";
	}

	@ResponseBody
	@RequestMapping("addEntity")
	@SystemLog(module = "系统管理", methods = "用户管理-新增用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	public String addEntity(String txtGroupsSelect) throws Exception {
		String sessionid = Common.findUserSessionId();
		if (sessionid != null) {
			ConsoleuserFormMap userFormMap = getFormMap(ConsoleuserFormMap.class);
			userFormMap.put("txtGroupsSelect", txtGroupsSelect);
			PasswordHelper passwordHelper = new PasswordHelper();
			userFormMap.put("password", "123456789");
			passwordHelper.encryptPassword(userFormMap);
			SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
			userFormMap.put("createTime", time.format(new Date()));
			userFormMap.put("addid", sessionid);
			userFormMap.save();
			if (!Common.isEmpty(txtGroupsSelect)) {
				String[] txt = txtGroupsSelect.split(",");
				UserRoleFormMap userGroupsFormMap = null;
				for (String roleId : txt) {
					userGroupsFormMap = new UserRoleFormMap();
					userGroupsFormMap.put("userId", userFormMap.get("id"));
					userGroupsFormMap.put("roleId", roleId);
					userGroupsFormMap.save();
				}
			}
		}
		return "success";
	}

	@ResponseBody
	@RequestMapping("addEntityManual")
	@SystemLog(module = "系统管理", methods = "用户管理-新增用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	public String addEntityManual(String txtGroupsSelect,ConsoleuserFormMap hewkeuserFormMap) throws Exception {
		String sessionid = Common.findUserSessionId();
		if (sessionid != null) {
			hewkeuserFormMap.put("txtGroupsSelect", txtGroupsSelect);
			PasswordHelper passwordHelper = new PasswordHelper();
			hewkeuserFormMap.put("password", "123456789");
			passwordHelper.encryptPassword(hewkeuserFormMap);
			SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
			hewkeuserFormMap.put("createTime", time.format(new Date()));
			hewkeuserFormMap.put("addid", sessionid);
			hewkeuserFormMap.save();
			if (!Common.isEmpty(txtGroupsSelect)) {
				String[] txt = txtGroupsSelect.split(",");
				UserRoleFormMap userGroupsFormMap = null;
				for (String roleId : txt) {
					userGroupsFormMap = new UserRoleFormMap();
					userGroupsFormMap.put("userId", hewkeuserFormMap.get("id"));
					userGroupsFormMap.put("roleId", roleId);
					userGroupsFormMap.save();
				}
			}
		}
		return "success";
	}
	
	
	@ResponseBody
	@RequestMapping("deleteEntity")
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-删除用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String deleteEntity() throws Exception {
		String[] ids = getParaValues("ids");
		for (String id : ids) {
			ConsoleuserFormMap userFormMap = new ConsoleuserFormMap();
			userFormMap.put("where", "id="+id);
			List<ConsoleuserFormMap> userlist = userFormMap.findByWhere();
			if (userlist.size() > 0) {
				String parentId=userlist.get(0).get("parentId").toString();
				userFormMap.put("parentId", id);
				List<ConsoleuserFormMap> list=userFormMap.findByNames();
				for(ConsoleuserFormMap u:list){
					u.put("parentId", parentId);
					u.update();
				}
			}
			new UserRoleFormMap().deleteByAttribute("userId", id);
			new ResUserFormMap().deleteByAttribute("userId", id);
			new ConsoleuserFormMap().deleteByAttribute("id", id);
		}
		return "success";
	}

	@RequestMapping("editUI")
	public String editUI(Model model) throws Exception {
		String id = getPara("id");
		if (Common.isNotEmpty(id)) {
			ConsoleuserFormMap userFormMap = new ConsoleuserFormMap().findById(id);
			model.addAttribute("user", userFormMap);
			ConsoleuserFormMap formMap = new ConsoleuserFormMap();
			String sessionid = Common.findUserSessionId();
			formMap.put("id", sessionid);
			List<ConsoleuserFormMap> list = userFormMap.mapper().findChildList(formMap);
			model.addAttribute("userlist", list);
		}
		return Common.BACKGROUND_PATH + "/system/user/edit";
	}

	@ResponseBody
	@RequestMapping("editEntity")
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-修改用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String editEntity(String txtGroupsSelect) throws Exception {
		ConsoleuserFormMap formMap = getFormMap(ConsoleuserFormMap.class);
		SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		formMap.put("createTime", time.format(new Date()));
		formMap.update();
		String userId = (String) formMap.get("id");
		if (Common.isNotEmpty(userId)) {
			UserRoleFormMap userGroupsFormMap = new UserRoleFormMap();
			userGroupsFormMap.put("userId", userId);
			userGroupsFormMap.deleteByNames();
			if (!Common.isEmpty(txtGroupsSelect)) {
				String[] txt = txtGroupsSelect.split(",");
				for (String roleId : txt) {
					userGroupsFormMap.put("roleId", roleId);
					userGroupsFormMap.save();
				}
			}
		}
		return "success";
	}

	@ResponseBody
	@RequestMapping("leave")
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-修改用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String leaveFun(String txtGroupsSelect) throws Exception {
		ConsoleuserFormMap userFormMap = new ConsoleuserFormMap();
		String[] ids = getParaValues("ids");
		if (ids[0] != null) {
			userFormMap.put("id", ids[0]);
			userFormMap.put("locked", 0);
			userFormMap.update();
		}
		return "success";
	}

	// unfreeze解除账号冻结
	@ResponseBody
	@RequestMapping("unfreeze")
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-修改用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String unfreezeFun(String txtGroupsSelect) throws Exception {
		ConsoleuserFormMap userFormMap = new ConsoleuserFormMap();
		String[] ids = getParaValues("ids");
		if (ids[0] != null) {
			userFormMap.put("id", ids[0]);
			userFormMap.put("locked", 1);
			userFormMap.update();
		}
		return "success";
	}

	// 密码修改
	@RequestMapping("updatePassword")
	public String updatePassword(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/user/updatePassword";
	}

	// 保存新密码
	@RequestMapping("editPassword")
	@ResponseBody
	@Transactional // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-修改密码") // 凡需要处理业务逻辑的.都需要记录操作日志
	public Map<String, Object> editPassword() throws Exception {
		// 当验证都通过后，把用户信息放在session里
		ConsoleuserFormMap userFormMap = getFormMap(ConsoleuserFormMap.class);
		Subject user = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getPrincipal().toString(),
				userFormMap.getStr("oldpassword"));
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			user.login(token);
			userFormMap.put("id", Common.findUserSessionId());
			userFormMap.put("accountName", user.getPrincipal());
			userFormMap.put("password", userFormMap.get("newpassword"));
			// 这里对修改的密码进行加密
			PasswordHelper passwordHelper = new PasswordHelper();
			passwordHelper.encryptPassword(userFormMap);
			userFormMap.update();
			map.put("results", "success");
			map.put("messages", "密码修改成功!");
		} catch (LockedAccountException lae) {
			token.clear();
			map.put("results", "error");
			map.put("messages", "用户已经被锁定不能登录，请与管理员联系！");
		} catch (AuthenticationException e) {
			token.clear();
			map.put("results", "error");
			map.put("messages", "用户或密码不正确！！");
		}
		return map;
	}

	/**
	 * 验证账号是否存在
	 * 
	 * @author framework Email：g5874589652@126.com date：2015-2-19
	 * @param name
	 * @return
	 */
	@RequestMapping("isExist")
	@ResponseBody
	public boolean isExist() {
		ConsoleuserFormMap account = getFormMap(ConsoleuserFormMap.class);
		account = account.findbyFrist();
		if (account == null) {
			return true;
		} else {
			return false;
		}
	}

	// 修改时的验证方法
	@ResponseBody
	@RequestMapping("editisExist")
	public boolean editisExist() {
		ConsoleuserFormMap userFormMap = getFormMap(ConsoleuserFormMap.class);
		// 先根据名称去找，没有就返回true
		// 有的话就判断是不是这id的记录，如果是的话也返回true
		// 否则返回false
		List<ConsoleuserFormMap> list = userFormMap.findByAttribute("userName", userFormMap.get("userName"));
		if (list.size() == 0) {
			return true;
		} else {
			if (list.size() >= 0) {
			}
			return false;
		}
	}

}